package com.example.lt.limit;

import com.example.lt.constant.RedisConstant;
import com.example.lt.context.BaseContext;
import com.example.lt.exception.BaseException;
import com.example.lt.util.RedisUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * @Author 小涛Tao
 * @Date: 2024/08/14/20:41
 * version 1.0 注释：切面类，对发布视频接口进行检查，同一个用户每一个小时不允许发布超过5个视频
 **/
@Aspect
@Component
public class LimiterAop {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 切面方法，判断
     * @param joinPoint 连接点
     * @param limiter 注解
     * @return
     * @throws Throwable
     */
    @Around("@annotation(limiter)")
    public Object restriction(ProceedingJoinPoint joinPoint, Limit limiter) throws Throwable {
        final Long userId = BaseContext.get();
        final int limitCount = limiter.limit();
        final long time = limiter.time();
        final String msg = limiter.msg();
        // 查询缓存是否存在
        final String key = RedisConstant.VIDEO_LIMIT + userId;
        final Object o1 = redisUtil.get(key);
        System.out.println("检查用户："+ userId +"是否在一小时内发布视频超过5个");
        if (ObjectUtils.isEmpty(o1)) {
            redisUtil.set(key, 1, time);
        } else {
            if (Integer.parseInt(o1.toString()) >= limitCount) {
                throw new BaseException(msg);
            }
            redisUtil.incr(key, 1);
        }

        final Object proceed = joinPoint.proceed();
        return proceed;
    }

}
